'use strict';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import {
  JDText,
} from '@areslabs/jdreact-core-lib';

export default class CountDown extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.value || 0
    };
  }

  componentDidMount() {
    this._startTimer();
  }

  componentWillUnmount() {
    this._endTimer();
  }

  render() {
    return (
      <JDText style={this.props.style}>
        {this.props.valueFormat ? this.props.valueFormat(this.state.value) : this.state.value}
      </JDText>
    )
  }

  _startTimer = () => {
    this.timer = setTimeout(function() {
      if (this.state.value >= this.props.limit) {
        this._endTimer();
        return;
      }
      this.setState({
        value: this.state.value + this.props.duration,
      });
      this._startTimer();
    }.bind(this), this.props.duration);
  }

  _endTimer = () => {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
    this.props.onEnd && this.props.onEnd(this.state.value);
  }
}

CountDown.propTypes = {
  value: PropTypes.number,
  duration: PropTypes.number,
  limit: PropTypes.number,
  onEnd: PropTypes.func,
  valueFormat: PropTypes.func,
}
